package com.sudo.onload.schedule;

import com.sudo.common.enums.UserParams;
import com.sudo.common.utils.JsonUtils;
import com.sudo.common.utils.RedisOperator;
import com.sudo.common.utils.SysInfoUtil;
import com.sudo.common.utils.SysInfoUtils;
import com.sudo.mapper.my.SysUserBehaviorMapper;
import com.sudo.pojo.SysUserBehavior;
import com.sudo.service.SysCpuLogService;
import com.sudo.service.SysMemLogService;
import com.sudo.service.SysUserBehaviorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author admins
 * @author：为道日损 2020-06-20 21:01
 * webSite：https://www.sudo.ren
 * @ EnableScheduling ；开启定时任务
 * @ EnableAsync ：开启多线程
 */
@Component
@EnableScheduling
@EnableAsync
public class MultiThreadScheduleTask {

    @Autowired
    private RedisOperator redisOperator;

    @Autowired
    private SysCpuLogService sysCpuLogService;

    @Autowired
    private SysMemLogService sysMemLogService;

    @Autowired
    private SysUserBehaviorMapper sysUserBehaviorMapper;

    @Async
    @Scheduled(fixedDelay = 300 * 1000)
    public void addUserBehaviorToMysqlFromRedis() {
        long len = redisOperator.llen(UserParams.REDIS_USER_BEHAVIOR.value);
        List<SysUserBehavior> sysUserBehaviorList = new ArrayList<>();
        for (int i = 0; i < len; i++) {
            String jsonData = redisOperator.rpop(UserParams.REDIS_USER_BEHAVIOR.value);
            SysUserBehavior sysUserBehavior = JsonUtils.jsonToPojo(jsonData, SysUserBehavior.class);
            sysUserBehaviorList.add(sysUserBehavior);
        }
        if (!CollectionUtils.isEmpty(sysUserBehaviorList)){
            sysUserBehaviorMapper.insertList(sysUserBehaviorList);
        }
    }

    @Async
    @Scheduled(fixedRate = 10*1000)
    public void getDynamicSysInfo() {
        sysCpuLogService.insertCpuLogToRedis();
        sysMemLogService.insertMemLogToRedis();
    }

    @Async
    @Scheduled(initialDelay = 10*60*1000,fixedRate = 10*60*1000)
    public void insertDynamicSysInfo() {
        sysCpuLogService.insertCpuLogFromRedisToMysql();
        sysMemLogService.insertMemLogFromRedisToMysql();
    }

}
